package com.mrd.serverconnect.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.mrd.serverconnect.R;
import com.mrd.serverconnect.been.AppAuth;
import com.mrd.serverconnect.been.IotLogin;
import com.mrd.serverconnect.been.OldAppAuth;
import com.mrd.serverconnect.been.ProduceRes;
import com.mrd.serverconnect.been.Product;
import com.mrd.serverconnect.listener.NoDoubleClickListener;
import com.mrd.serverconnect.net.ServerCongig;
import com.mrd.serverconnect.util.AppLifeManager;
import com.mrd.serverconnect.util.DisplayUtil;
import com.mrd.serverconnect.util.SPUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import io.reactivex.functions.Consumer;
import okhttp3.MediaType;

public class PoduceActivity extends BaseActivity {

    private static final String TAG = "v";
    private Button sn_w;
    private ProgressDialog proDialog;
    private RxPermissions rxPermissions;
    private EditText sn_ed;
    private Context context;
    private RadioGroup mRadioGroup;
    private String productId;
    private RelativeLayout rlLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poduce);
        context = this;

        String sn = SPUtils.getString(PoduceActivity.this, SPUtils.SN);
        findView();
        initEvent();
        if (TextUtils.isEmpty(sn)) {
            getProductionList();
        } else {
            rlLoading.setVisibility(View.VISIBLE);
            initAuth();
        }
    }

    private void initAuth() {
        String accessKey = SPUtils.getAccessKey(context);
        String secretKey = SPUtils.getSecretKey(context);
        String sn = SPUtils.getString(context, SPUtils.SN);
        if (TextUtils.isEmpty(accessKey) || TextUtils.isEmpty(secretKey)) {
            HashMap<Object, Object> params = new HashMap<>();
            params.put("sn", sn);
            final PostRequest<String> authPost = OkGo.<String>post(ServerCongig.OldFactoryBaseUrl + ServerCongig.old_auth)
                    .tag(this)
                    .upString(new Gson().toJson(params), MediaType.parse("application/json;charset=utf8"));
            StringCallback ahthCallback = new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    String json = response.body().toString();
                    OldAppAuth appAuth = new Gson().fromJson(json, OldAppAuth.class);

                    String accessKey1 = appAuth.getData().getAccessKey();
                    String secretKey1 = appAuth.getData().getSecretKey();

                    SPUtils.writeAccessKey(context, accessKey1, secretKey1);

                    requestNewAhth(accessKey1, secretKey1);
                }

                @Override
                public void onError(Response<String> response) {

                }

            };
            authPost.execute(ahthCallback);
        } else {
            requestNewAhth(accessKey, secretKey);
        }
    }

    private void requestNewAhth(String accessKey, String secretKey) {
        /**
         * 去鉴权
         */
        HashMap<Object, Object> params = new HashMap<>();
        params.put("accessKey", accessKey);
        params.put("secretKey", secretKey);
        final PostRequest<String> authPost = OkGo.<String>post(ServerCongig.FactoryBaseUrl + ServerCongig.auth)
                .tag(this)
                .headers("Content-Type", "application/json")
                .upString(new Gson().toJson(params), MediaType.parse("application/json;charset=utf8"));
        StringCallback ahthCallback = new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.e("鉴权", "onSuccess: " + response.body().toString());
                String json = response.body().toString();
                AppAuth appAuth = new Gson().fromJson(json, AppAuth.class);
                if (appAuth.getRet() == 10000) {
                    //iot登录
                    mpLogin(appAuth);
                } else {
                    //ToastUtils.showShort(appAuth.getRet()+"");
                    reAuth(response);
                }
            }

            @Override
            public void onError(Response<String> response) {
                reAuth(response);
            }

            private void reAuth(Response<String> response) {
                Log.d("reAuth", "鉴权请求失败，5秒后重试:==" + response.message());
                final StringCallback stringCallback = this;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        authPost.execute(stringCallback);
                    }
                }).start();

            }
        };
        authPost.execute(ahthCallback);
    }

    /**
     * iot登录
     *
     * @param appAuth
     */
    private void mpLogin(final AppAuth appAuth) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        OkGo.<String>post("http://" + appAuth.getUrl() + ServerCongig.iotLogin)
                .tag(this)
                .headers("Content-Type", "application/json")
                .headers("Host", appAuth.getUrl())
                .headers("accesskey", SPUtils.getAccessKey(context))
                .headers("secretKey", SPUtils.getSecretKey(context))
                .headers("version", AppLifeManager.getAppVersionName(context))
                .headers("signal", appAuth.getSecret())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e(TAG, "onSuccess: " + response.body().toString());
                        IotLogin iotLogin = new Gson().fromJson(response.body().toString(), IotLogin.class);

                        String wsUrl = iotLogin.getUrl();
                        String token = iotLogin.getToken();
                        SPUtils.putString(context, SPUtils.TOKEN, token);
                        SPUtils.putString(context, SPUtils.BASEURL, appAuth.getUrl());

                        if (token != null) {
                            Log.e(TAG, "onSuccess_token: " + token);
                            startActivity(new Intent(context, MainActivity.class));
                            finish();
                        }
                    }
                });
    }


    private void findView() {
        sn_w = (Button) findViewById(R.id.sn_w);
        sn_ed = (EditText) findViewById(R.id.sn_ed);
        mRadioGroup = (RadioGroup) findViewById(R.id.mRadioGroup);
        rlLoading = (RelativeLayout) findViewById(R.id.rl_loading);
    }

    private void initEvent() {
        sn_w.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                proDialog = ProgressDialog.show(PoduceActivity.this, "提示", "入库中，请稍后");
                initPermissions();
            }
        });
    }

    /**
     * 获取产品列表---大屏盒子--影音盒子
     */
    List<Product.DataEntity> productData = new ArrayList<>();

    private void getProductionList() {
        HashMap<String, Object> params = new HashMap<>();
        PostRequest<String> postRequest = OkGo.<String>post(ServerCongig.MpBaseUrl + ServerCongig.production)
                .tag(this).upString(new Gson().toJson(params), MediaType.parse("application/json;charset=utf8"));
        StringCallback stringCallback = new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                Log.e(TAG, "onSuccess: " + response.body().toString());
                Product product = new Gson().fromJson(response.body(), Product.class);
                int index = 0;
                if (product != null) {
                    productData = product.getData();
                    for (int i = 0; i < productData.size(); i++) {
                        RadioButton button = new RadioButton(context);
                        button.setText(productData.get(i).getProductName());
                        button.setId(i);
                        mRadioGroup.addView(button);

                        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) button
                                .getLayoutParams();
                        layoutParams.setMargins(0, 0, DisplayUtil.dip2px(context, 10), 0);//4个参数按顺序分别是左上右下
                        button.setLayoutParams(layoutParams);
                        index++;
                    }
                }
            }
        };
        postRequest.execute(stringCallback);

        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                productId = productData.get(i).getProductId();
            }
        });

    }


    private void initPermissions() {
        rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_SETTINGS, Manifest.permission.WAKE_LOCK)
                .subscribe(new Consumer<Boolean>() {
                               @Override
                               public void accept(Boolean aBoolean) throws Exception {
                                   if (aBoolean) {//true表示获取权限成功（注意这里在android6.0以下默认为true）
                                       Log.d("RxPermissions", "权限成功（注意这里在android6.0以下默认为true）");
                                       Toast.makeText(PoduceActivity.this, "权限成功（注意这里在android6.0以下默认为true）", Toast.LENGTH_LONG).show();
                                       proDialog.setMessage("正在写入SN");
                                       initSn();
                                   } else {
                                       if (proDialog != null) {
                                           proDialog.dismiss();
                                       }
                                       showDialogTips("入库失败,必须同意权限注册");
                                       Log.e("RxPermissions", "权限注册失败，请卸载后重装");
                                   }
                               }
                           }
                );
    }


    private void initSn() {
        if (productId == null || TextUtils.isEmpty(productId)) {
            if (proDialog != null) {
                proDialog.dismiss();
            }
            showDialogTips("请选择入库类型");
            return;
        }

        String sn = sn_ed.getText().toString();
        if (!TextUtils.isEmpty(sn)) {
            SPUtils.putString(PoduceActivity.this, SPUtils.SN, sn);
            proDialog.setMessage("SN写入成功");
            DevicesProduce();
        } else {
            if (proDialog != null) {
                proDialog.dismiss();
            }
            showDialogTips("入库失败,SN不能为空");
        }
    }


    /**
     * 入库
     */
    private void DevicesProduce() {
        ////  请求服务服 设备入库  写入
        HashMap<String, Object> params = new HashMap<>();
        params.put("sn", SPUtils.getString(context, SPUtils.SN));
        params.put("version", AppLifeManager.getAppVersionName(context));
        params.put("mac", AppLifeManager.getMAC());
        params.put("productId", productId);
        OkGo.<String>post(ServerCongig.MpBaseUrl + ServerCongig.produce)
                .tag(this)
                .upString(new Gson().toJson(params), MediaType.parse("application/json;charset=utf8"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e(TAG, "onSuccess: " + response.body().toString());
                        ProduceRes produceRes = new Gson().fromJson(response.body(), ProduceRes.class);
                        if (produceRes.getRet() == 0) {
                            sn_w.setEnabled(false);
                            showDialogTips("已入库,请在mp上分配平台后重启设备验证");
                        } else {
                            SPUtils.putString(context, SPUtils.SN, "");
                            showDialogTips("入库失败:" + produceRes.getMsg());
                        }
                        if (proDialog != null) {
                            proDialog.dismiss();
                        }
                    }
                });
    }


    public void showDialogTips(String Text) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage(Text)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.create().show();


    }
}
